/**
 * Copyright 2024/3/24 the original brandnewdata.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zlb.envmodify.service;

import com.zlb.envmodify.transform.config.EnvSettingConfig;
import com.zlb.envmodify.transform.config.ModifyClassConfig;
import org.codehaus.plexus.util.StringUtils;

import java.io.File;
import java.io.InputStream;
import java.util.Properties;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @Description
 * @ClassName SimpleEnvModifyServiceImpl
 * @Author zhulb
 * @Date 2024/3/24 11:06
 * @Version 0.0.1
 */
public class SimpleEnvModifyServiceImpl implements EnvModifyService {

    static final Logger logger = Logger.getLogger(SimpleEnvModifyServiceImpl.class.getName());

    static String CONFIG_ENV_PREFIX = "config.zlb.env";

    static String CONFIG_DNS_PREFIX = "config.zlb.dns";
    static final String ENV_SETTING_FILE_NAME = "envSetting.properties";

    static final String ENV_MODIFY_CLASS_CONFIG_FILE_NAME = "envmodify.config";

    /**
     * 启动参数
     */
    private String agentArgs;

    /**
     * 配置文件存放目录
     */
    private String configPath;

    /**
     * pom中定义的版本号
     */
    private static final String VERSION;

    /**
     * pom中定义的groupId
     */
    private static final String GROUP_ID;

    /**
     * pom中定义的artifactId
     */
    private static final String ARTIFACT_ID;

    static {
        String version = null, groupId = null, artifactId = null;
        try {
            InputStream inputStream = SimpleEnvModifyServiceImpl.class.getClassLoader().getResourceAsStream("META-INF/maven/com.zlb/zlb-java-envmodify/pom.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            version = properties.getProperty("version");
            artifactId = properties.getProperty("artifactId");
            groupId = properties.getProperty("groupId");
            logger.info("插件信息: artifactedId=" + artifactId + ",groupId=" + groupId + ",version=" + version);
        } catch (Exception e) {
            throw new RuntimeException("获取版本号异常!");
        } finally {
            VERSION = version;
            GROUP_ID = groupId;
            ARTIFACT_ID = artifactId;
        }
    }

    @Override
    public EnvSettingConfig getEnvSettingConfig() {
        return getEnvSettingConfig(() -> {
            return getConfigPath();
        });
    }

    @Override
    public String getSystemCode() {
        return StringUtils.isEmpty(agentArgs) ? System.getenv("SYSTEM_CODE") : agentArgs;
    }

    @Override
    public void setAgentArgs(String agentArgs) {
        this.agentArgs = agentArgs;
    }

    @Override
    public String getConfigEnvPrefix() {
        return CONFIG_ENV_PREFIX;
    }

    @Override
    public String getConfigDnsPrefix() {
        return CONFIG_DNS_PREFIX;
    }

    @Override
    public ModifyClassConfig getEnvModifyClassConfig() {
        return new ModifyClassConfig(getConfigPath() + File.separator + ENV_MODIFY_CLASS_CONFIG_FILE_NAME);
    }

    private String getConfigPath() {
        if (configPath == null) {
            synchronized (SimpleEnvModifyServiceImpl.class) {
                if (configPath == null) {
                    logger.info("|SimpleEnvModifyServiceImpl|getConfigPath|"+System.getProperty("user.home")+"|");
                    configPath = System.getProperty("user.home") + File.separator + ARTIFACT_ID + "@" + VERSION;
                }
            }
        }
        return configPath;
    }

    private EnvSettingConfig getEnvSettingConfig(Supplier<String>... getFilePaths) {
        File envFile = null;
        for (Supplier<String> getFilePath : getFilePaths) {
            envFile = new File(getFilePath.get() + File.separator + ENV_SETTING_FILE_NAME);
            if (envFile.exists()) {
                break;
            }
            envFile = null;
        }

        if (envFile != null) {
            return new EnvSettingConfig(envFile);
        }
        logger.log(Level.WARNING, "缺失配置文件：" + ENV_SETTING_FILE_NAME + "，项目打包即可解决。");
        return null;
    }
}
